<?php

namespace app\stock\controller\Manage;

use think\Controller;

class Visit extends Controller
{
    protected $VisitModel = null;
    protected $BusinessModel = null;

    public function __construct()
    {
        parent::__construct();

        $this->VisitModel = model('Business.Visit');
        $this->BusinessModel = model('Business.Business');
    }

    public function index()
    {
        $adminid = $this->request->param('adminid', 0, 'trim');

        $admin = model('Admin')->find($adminid);

        if (!$admin) {
            $this->error('管理员不存在');
        }

        if ($admin['status'] !== 'normal') {
            $this->error('当前账号已禁用，无法操作');
        }

        $data = $this->VisitModel->with(['business'])->where(['visit.adminid' => $adminid])->order('createtime DESC')->select();

        if (!$data) {
            $this->error('暂无数据');
        }

        $this->success('查询成功', null, $data);
    }

    public function business()
    {
        $adminid = $this->request->param('adminid', 0, 'trim');

        $Admin = model('Admin')->find($adminid);

        if (!$Admin) {
            $this->error('管理员不存在');
        }

        $BusinessData = $this->BusinessModel->where(['adminid' => $adminid])->select();

        if (!$BusinessData) {
            $this->error('暂无数据');
        }

        $this->success('查询成功', null, $BusinessData);
    }

    public function add()
    {
        $adminid = $this->request->param('adminid', 0, 'trim');
        $busid = $this->request->param('busid', 0, 'trim');
        $content = $this->request->param('content', '', 'trim');

        $admin = model('Admin')->find($adminid);

        if (!$admin) {
            $this->error('管理员不存在');
        }

        if ($admin['status'] !== 'normal') {
            $this->error('当前账号已禁用，无法操作');
        }

        $business = $this->BusinessModel->find($busid);

        if (!$business) {
            $this->error('回访客户不存在');
        }

        $data = [
            'busid' => $busid,
            'adminid' => $adminid,
            'content' => $content
        ];

        $result = $this->VisitModel->validate('common/Business/Visit')->save($data);

        if ($result === FALSE) {
            $this->error($this->VisitModel->getError());
        } else {
            $this->success('回访记录新增成功');
        }
    }
}
